package com.ep.thirdPlatformProject.system.exception;


import com.ep.thirdPlatformProject.system.handler.ErrorResponse;
import com.ep.thirdPlatformProject.system.handler.PrintStack;
import com.fasterxml.jackson.core.JsonParseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalResponseBodyHandler {

    // 异常处理器
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ErrorResponse handleException(Exception e) {
        // 这里可以根据需要记录异常信息，发送通知等
        log.error("发生异常: {}", e.getMessage());
        String str = PrintStack.doPrintStack(e, 5, new StringBuilder());
        // 返回错误信息
        return new ErrorResponse(-1, "服务器或者网络发生异常，请稍后重试!", str);
    }

    /**
     * 处理方法参数异常
     *
     * @param e e
     * @return {@link String }
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public ErrorResponse handleJsonParseException(JsonParseException e) {
        String error = e.getMessage();

        log.error("json解析失败：{}", error);
        return new ErrorResponse(-1, "json解析失败了", error);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        assert error != null;
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        log.error("参数验证失败：{}", message);
        return new ErrorResponse(-1, "参数验证失败", message);
    }

}
